<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="厂房编号" prop="roomCode">
        <el-input v-model="queryParams.roomCode" placeholder="请输入厂房编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="厂房名称" prop="roomName">
        <el-input v-model="queryParams.roomName" placeholder="请输入厂房名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['rooms:roomsinformation:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['rooms:roomsinformation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rooms:roomsinformation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['rooms:roomsinformation:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomsinformationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="厂房编号" align="center" prop="roomCode" />
      <el-table-column label="厂房名称" align="center" prop="roomName" />
      <el-table-column label="状态评估" align="center" prop="stateEvaluation" />
      <el-table-column label="建成日期" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['rooms:roomsinformation:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['rooms:roomsinformation:remove']">删除</el-button>
          <!-- 新增的详细查看按钮 -->
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['rooms:roomsinformation:view']">查看设施</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改厂房信息目录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="厂房名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入厂房名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看设施弹窗 -->
    <el-dialog title="设施列表" :visible.sync="facilityDialogVisible" width="70%" :close-on-click-modal="false">
      <el-table v-loading="loading" :data="facilityList" border style="width: 100%; margin-top: 10px;">
        <el-table-column prop="facilityCode" label="设施编号" align="center"></el-table-column>
        <el-table-column prop="facilityName" label="设施名称" align="center"></el-table-column>
        <el-table-column prop="facilityType" label="设施类型" align="center"></el-table-column>
        <el-table-column prop="modelSpec" label="型号规格" align="center"></el-table-column>
        <el-table-column prop="manufacturer" label="生产厂家" align="center"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listRoomsinformation, getRoomsinformation, delRoomsinformation, addRoomsinformation, updateRoomsinformation } from "@/api/rooms/roomsinformation"

// 新增设施接口（新JS文件）
import { getFacilitiesByRoomCode } from "@/api/rooms/Facilities"

export default {
  name: "Roomsinformation",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 厂房信息目录表格数据
      roomsinformationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomCode: null,
        roomName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },


      // --------------- 新增以下设施相关变量 ---------------
      // 设施列表数据（模板中绑定的表格数据）
      facilityList: [],
      // 设施弹窗是否显示（控制弹窗开关）
      facilityDialogVisible: false,
      // 设施列表加载状态（控制弹窗内的加载动画）
      facilityLoading: false
      // ---------------------------------------------------
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询厂房信息目录列表 */
    getList() {
      this.loading = true
      listRoomsinformation(this.queryParams).then(response => {
        this.roomsinformationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        roomCode: null,
        roomName: null,
        stateEvaluation: null,
        illuminanceStandard: null,
        createdAt: null,
        isDelete: null,
        id: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加厂房信息目录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRoomsinformation(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改厂房信息目录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRoomsinformation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRoomsinformation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除厂房信息目录编号为"' + ids + '"的数据项？').then(function () {
        return delRoomsinformation(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rooms/roomsinformation/export', {
        ...this.queryParams
      }, `roomsinformation_${new Date().getTime()}.xlsx`)
    },

    /**
     * 查看设施按钮操作
     * 点击后打开弹窗并加载对应厂房的设施数据
     */
    handleView(row) {
      // 校验厂房编号是否存在
      if (!row || !row.roomCode) {
        this.$modal.msgError("厂房编号不存在，无法查询设施");
        return;
      }

      // 打开弹窗
      this.facilityDialogVisible = true;
      // 显示加载状态
      this.facilityLoading = true;
      // 清空历史数据
      this.facilityList = [];

      // 调用接口查询设施列表
      getFacilitiesByRoomCode(row.roomCode, {
        pageNum: 1, // 分页参数：第一页
        pageSize: 100 // 可根据需求调整每页条数，或使用默认值
      })
        .then((response) => {
          // 接口成功回调
          if (response && response.code === 200) {
            // 假设后端返回格式为 {code:200, rows: [...]}
            this.facilityList = response.rows || [];
          } else {
            this.$modal.msgWarning("获取设施数据失败：" + (response.msg || "未知错误"));
            this.facilityList = [];
          }
        })
        .catch((error) => {
          // 接口异常回调
          console.error("查询设施列表失败：", error);
          this.$modal.msgError("网络异常，无法获取设施数据");
          this.facilityList = [];
        })
        .finally(() => {
          // 无论成功失败，都关闭加载状态
          this.facilityLoading = false;
        });
    },

    /** 日期格式化方法 - 确保这个方法在 methods 里 */
    formatDate(dateString) {
      if (!dateString) {
        return "-";
      }
      try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        console.error("日期格式化失败：", error);
        return dateString;
      }
    }


  }
}




</script>
